package evolutionaryLoop.selectionMechanisme;

import java.util.ArrayList;
import java.util.List;

import evolutionaryLoop.Population;

public class SigmaSelection extends GlobalSelectionMechanisme{
	
	@Override
	public void setPopulation(Population population) {
		phenotypeList = population.getPopulationList(); 
		
		double avgFitness = getAvgFitness(); 
		double standardDiviation = getStandardDivation(); 
		
		if (standardDiviation == 0){
			handleZeroSD(); 
			return; 
		}
		
		List<Double> probabilityList = new ArrayList<Double>(phenotypeList.size());
		for (int i = 0; i < phenotypeList.size(); i++){
			probabilityList.add(sigmaScaling(phenotypeList.get(i).getFitness(), avgFitness, standardDiviation));
		}
		scaledFitnessList = probabilityList; 
		double minFitness = minScaledFitness(); 
		if (minFitness < 0 ){
			double delta = -minFitness; 
			for (int i = 0; i < scaledFitnessList.size(); i++) {
				scaledFitnessList.set(i, scaledFitnessList.get(i)+delta); 
			}
		}
		normalizeScaledFitness(); 
	}

	private double sigmaScaling(double fitness, double avgFitness, double standardDiviation){
		return 1 + (fitness-avgFitness)/(2*standardDiviation); 
	}

	private void handleZeroSD() {
		scaledFitnessList = new ArrayList<Double>(phenotypeList.size()); 
		for (int i = 0; i < phenotypeList.size(); i++) {
			scaledFitnessList.add((double) 1); 
		}
		normalizeScaledFitness();
	}

	public String toString(){
		return "Sigma selection"; 
	}
	
}
